package com.mycjj.android.activity;

import java.util.HashMap;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mycjj.android.ProjectDataManage;
import com.mycjj.android.R;
import com.mycjj.android.bean.CarInfoBaseBean;
import com.mycjj.android.bean.LoginMemberBean;
import com.mycjj.android.bean.MemberBean;
import com.mycjj.android.bean.RegisterUserBean;
import com.mycjj.android.bean.TreeElement;
import com.mycjj.android.bean.CarInfoBaseBean.CarInfo;
import com.mycjj.android.bean.MemberBean.Member;
import com.mycjj.android.bean.MemberBean.MemberCar;
import com.mycjj.android.bean.MemberBean.MemberStore;
import com.mycjj.android.http.ProjectHttpRequestImpl;
import com.mycjj.android.http.ProjectHttpRequestInterface;
import com.mycjj.android.util.Preferences;
import com.mycjj.android.util.Utils;
import com.tencent.android.tpush.XGPushManager;

public class LoginActivity extends BaseActivity implements Callback{
	
	private EditText et_user_name,et_user_pwd;
	private Button btn_reg,btn_login;
	private TextView tv_version;
	
	private ImageView iv_qq_login,iv_sina_login;
	private mPlatformActionListener mPlatfListener;
	
	private static final int MSG_USERID_FOUND = 1;
	private static final int MSG_LOGIN = 2;
	private static final int MSG_AUTH_CANCEL = 3;
	private static final int MSG_AUTH_ERROR= 4;
	private static final int MSG_AUTH_COMPLETE = 5;
	private String loginType = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_login);
		mActManager.pushActivity(REGISTER_KEY, this);
		ShareSDK.initSDK(this);
		mPlatfListener = new mPlatformActionListener();
		init();
		initListener();
	}

	private TextView tv_find_pwd;
	private void init(){
		et_user_name = (EditText)findViewById(R.id.et_user_name);
		et_user_pwd  = (EditText)findViewById(R.id.et_user_pwd);
		btn_reg = (Button)findViewById(R.id.btn_reg);
		btn_login = (Button)findViewById(R.id.btn_login);
		tv_find_pwd = (TextView)findViewById(R.id.tv_find_pwd);
		tv_version = (TextView) findViewById(R.id.tv_version);
		tv_version.setText("版本号:"+Utils.getVerName(this));
		iv_qq_login = (ImageView)findViewById(R.id.iv_qq_login);
		iv_sina_login = (ImageView)findViewById(R.id.iv_sina_login);
		
		String accountNum = Preferences.getSharedPreferences(mApp, "accountNum", "");
		if(!TextUtils.isEmpty(accountNum)){
			String password = Preferences.getSharedPreferences(mApp, "password", "");
			et_user_name.setText(accountNum);
			et_user_pwd.setText(password);
		}
	}
	
	private void initListener(){
		
		btn_login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String account = et_user_name.getText().toString().trim();
				String password = et_user_pwd.getText().toString().trim();
				String login_type = "web";
				if(TextUtils.isEmpty(account)){
					Toast.makeText(LoginActivity.this, "account is empty!!!", Toast.LENGTH_LONG).show();
					return;
				}else if(TextUtils.isEmpty(password)){
					Toast.makeText(LoginActivity.this, "password is empty!!!", Toast.LENGTH_LONG).show();
					return;
				}
				doLogin(account,password,login_type);
			}
		});
		
		btn_reg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				doRegister();
			}
		});
		
		tv_find_pwd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(LoginActivity.this,FindPwdActivity.class);
				intent.putExtra("title", "找回密码");
				intent.putExtra("type", "2");
				startActivity(intent);
			}
		});
		
		iv_qq_login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				thridLogin(1);
			}
		});
		iv_sina_login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				thridLogin(2);
			}
		});
		
	}
	private void doRegister(){
		Intent intent = new Intent(this,RegisterActivity.class);
		startActivity(intent);
	}
	
	private void doLogin(final String account,final String password,String login_type){
		Log.e("mark", "account:"+account);
		Log.e("mark", "password:"+password);
		request = new ProjectHttpRequestImpl(this, true);
		RequestParams params = new RequestParams();
		params.put("account", account);
		params.put("password", password);
		params.put("login_type", login_type);
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		params.put("device_type", "android");
		request.requestLoginUserWithDoneHandler("", params, new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				Log.e("mark", "login response:"+content);
				LoginMemberBean bean = ProjectDataManage.getInstance().getLoginMemberBean();
				
				if(bean != null){
					MemberBean memberBean = (MemberBean)bean.getData();
					if(memberBean != null){
						Member member = memberBean.getMember_arr();
						Preferences.setEditor(LoginActivity.this, "user_token", memberBean.getToken());
						if(member != null){//用户积分信息
							int points = 0,totalPoints = 0;
							try{
								points = Integer.parseInt(member.getMember_points());
							}catch(Exception e){
								points = 0;
							}
							
							try{
								totalPoints = Integer.parseInt(member.getMember_total_points());
							}catch(Exception e){
								totalPoints = 0;
							}
							
							dataManager.setPoints(points);
							dataManager.setTotalPoints(totalPoints);
							String mobile = member.getMember_mobile();
							//设置推送别名
							XGPushManager.registerPush(getApplicationContext(),"mycjj_android_"+mobile);
							//设置手机号,用于修改手机界面赋值
							Preferences.setEditor(mApp, "mobile", mobile);
							//记住用户名密码
							Preferences.setEditor(mApp, "password", password);
							Preferences.setEditor(mApp, "accountNum", account);
						}
						
						MemberStore store = memberBean.getMember_stores();
						if(store != null){//4s店信息
							Log.i("info", "kakakka=="+store.getStore_point());
							Preferences.setEditor(mApp, "storeId", store.getStore_id());
							Preferences.setEditor(mApp, "storeName", store.getStore_name());
							Preferences.setEditor(mApp, "storeAddress", store.getStore_address());
							Preferences.setEditor(mApp, "storeTel", store.getStore_tel());
							Preferences.setEditor(mApp, "storePoint", store.getStore_point());
						}
						
						MemberCar car = memberBean.getMember_cars();
						String default_car_id = "";
						if(car != null){//车辆信息
							String carId = car.getId();
							Preferences.setEditor(mApp, "carId", carId);
							Preferences.setEditor(mApp, "carNum", car.getPlate_number());
							
							String old_account = Preferences.getSharedPreferences(mApp, "account", "");
							default_car_id = carId;
							if(account.equals(old_account)){//如果帐号相等,获取default_car_id
								default_car_id = Preferences.getSharedPreferences(mApp, "default_car_id", carId);
							}else{//帐号不等，就不获取default_car_id,default_car_id 默认返回的carId，除非用户在我的车辆界面进行修改
								Preferences.setEditor(mApp, "account", account);
							}
							Preferences.setEditor(mApp, "default_car_id", default_car_id);
//							Preferences.setEditor(mApp, "default_car_id", carId);
						}else{
							Log.e("mark", "no car!!");
						}
						
						if(bean.getCode() == 200){
							Log.i("info", "---code200="+memberBean.getToken());
							//如果为空，说明没有绑定过，这种情况一般不会发生，跳转到Register2界面
							if(TextUtils.isEmpty(default_car_id)){
								Intent intent = new Intent(LoginActivity.this,Register2Activity.class);
								startActivity(intent);
							}else{
								getCarInfo(default_car_id);
							}
						}else if(bean.getCode() == 300){
							Toast.makeText(LoginActivity.this, "请绑定手机号!", Toast.LENGTH_LONG).show();
							Intent intent = new Intent(LoginActivity.this,BindTelActivity.class);
							startActivity(intent);
						}else if(bean.getCode() == 400){
							if(TextUtils.isEmpty(default_car_id)){
								Intent intent = new Intent(LoginActivity.this,Register2Activity.class);
								startActivity(intent);
							}else{
								Toast.makeText(LoginActivity.this, "请绑定您服务点!", Toast.LENGTH_LONG).show();
								Intent intent = new Intent(LoginActivity.this,BindStoreActivity.class);
								intent.putExtra("type_action", 1);
								startActivity(intent);
							}
						}else{
							Toast.makeText(LoginActivity.this, bean.getMsg(), Toast.LENGTH_LONG).show();
						}
					}else{
						Toast.makeText(LoginActivity.this, "用户名密码错误!", Toast.LENGTH_LONG).show();
					}
				}else {
					Toast.makeText(LoginActivity.this, "bean is empty!", Toast.LENGTH_LONG).show();
				}
				
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				Toast.makeText(LoginActivity.this, content, Toast.LENGTH_LONG).show();
			}
		});
	}
	
	private void getCarInfo(String carId){
		request = new ProjectHttpRequestImpl(this, true);
		RequestParams params = new RequestParams();
		params.put("car_id", carId);
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		params.put("token",
				Preferences.getSharedPreferences(this, "user_token", ""));
		request.requestUserCarGetWithDoneHandler("", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						CarInfoBaseBean baseBean = dataManager.getCarInfoBaseBean();
						if (baseBean != null) {
							if (baseBean.getCode() == 200) {
								Toast.makeText(LoginActivity.this, "登陆成功!!!", Toast.LENGTH_LONG).show();
								CarInfo info = baseBean.getData();
								Preferences.setEditor(mApp, "default_car_num", info.getNative_plate());
//								TreeElement element = new TreeElement();
//								element.setBrandId(info.getBrand1_id());
//								element.setBrandId1(info.getBrand2_id());
//								element.setBrandId2(info.getBrand3_id());
//								element.setBrandId3(info.getBrand4_id());
//								element.setTitle(info.getCar_name());
								
								dataManager.setDefaultCarInfo(info);
								Intent intent = new Intent(LoginActivity.this,MainActivity.class);
								startActivity(intent);
								LoginActivity.this.finish();
								
							} else {
								Toast.makeText(
										LoginActivity.this,
										baseBean.getMsg(),
										Toast.LENGTH_SHORT).show();
							}
						}
					}
					@Override
					public void onFailure(Throwable error, String content) {
						Toast.makeText(
								LoginActivity.this,"error msg:"+content,
								Toast.LENGTH_SHORT).show();
					}
				}
		
		
	
				);
	}
	//第三方登录
	private void login(String login_type,String open_id,String open_info){
		request = new ProjectHttpRequestImpl(this, true);
		RequestParams params = new RequestParams();
		params.put("login_type", login_type);
		params.put("open_id", open_id);
		params.put("open_info", open_info);
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		request.requestLoginUserWithDoneHandler("", params, new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				LoginMemberBean bean = ProjectDataManage.getInstance().getLoginMemberBean();
				
				if(bean != null){
					MemberBean memberBean = (MemberBean)bean.getData();
					Member member = memberBean.getMember_arr();
					MemberStore store = memberBean.getMember_stores();
					if(store == null ){
						Log.i("info", "--kaka--store==null");
					}
					if(store != null){
						Log.i("info", "--kaka--store="+store.getStore_point());
						Preferences.setEditor(mApp, "storeId", store.getStore_id());
						Preferences.setEditor(mApp, "storeName", store.getStore_name());
						Preferences.setEditor(mApp, "storeAddress", store.getStore_address());
						Preferences.setEditor(mApp, "storeTel", store.getStore_tel());
						Preferences.setEditor(mApp, "storePoint", store.getStore_point());
					}
					MemberCar car = memberBean.getMember_cars();
					if(car != null){
						Preferences.setEditor(mApp, "carId", car.getId());
						Preferences.setEditor(mApp, "carNum", car.getPlate_number());
					}
					
					if(bean.getCode() == 200){
						Log.e("mark", content);
						
						Log.i("info", "---斯蒂芬斯蒂芬斯蒂芬是的="+memberBean.getToken());
						Preferences.setEditor(LoginActivity.this, "user_token", memberBean.getToken());
						Toast.makeText(LoginActivity.this, "登陆成功!!!", Toast.LENGTH_LONG).show();
						Intent intent = new Intent(LoginActivity.this,MainActivity.class);
						startActivity(intent);
					}else if(bean.getCode() == 400){
						Log.i("info", "---斯蒂芬斯蒂芬斯蒂芬是的="+memberBean.getToken());
						Preferences.setEditor(LoginActivity.this, "user_token", memberBean.getToken());
						Toast.makeText(LoginActivity.this, "请绑定您服务点!", Toast.LENGTH_LONG).show();
						Intent intent = new Intent(LoginActivity.this,BindStoreActivity.class);
						startActivity(intent);
					}else{
						Toast.makeText(LoginActivity.this, bean.getMsg(), Toast.LENGTH_LONG).show();
					}
				}else {
					Toast.makeText(LoginActivity.this, "bean is empty!", Toast.LENGTH_LONG).show();
				}
				
			}
		});
	}
	
	private void thridLogin(int typeId){
		if(typeId == 1){
			loginType = "tencent";
			authorize(new QZone(this));
		}else if(typeId == 2){
			loginType = "sina";
			authorize(new SinaWeibo(this));
		}
	}
	
	private void authorize(Platform plat) {
		if (plat == null) {
			return;
		}
		
		if(plat.isValid()) {
			String userId = plat.getDb().getUserId();
			if (!TextUtils.isEmpty(userId)) {
				UIHandler.sendEmptyMessage(MSG_USERID_FOUND, this);
				//TODO
				login(loginType, userId, null);
				return;
			}
		}
		plat.setPlatformActionListener(mPlatfListener);
		plat.SSOSetting(true);
		plat.showUser(null);
	}
	
	//授权等回调方法
	public class mPlatformActionListener implements PlatformActionListener{
		@Override
		public void onCancel(Platform arg0, int action) {
			//取消授权
			if (action == Platform.ACTION_USER_INFOR) {
				UIHandler.sendEmptyMessage(MSG_AUTH_CANCEL, LoginActivity.this);
			}
		}
		@Override
		public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
			// 成功
			if (action == Platform.ACTION_USER_INFOR) {
				UIHandler.sendEmptyMessage(MSG_AUTH_COMPLETE, LoginActivity.this);
				
				String open_info = Utils.MapToJsonStr(res);
				login(loginType, platform.getDb().getUserId(), open_info);
			}
		}
		@Override
		public void onError(Platform arg0, int action, Throwable arg2) {
			//失败！
			if (action == Platform.ACTION_USER_INFOR) {
				UIHandler.sendEmptyMessage(MSG_AUTH_ERROR, LoginActivity.this);
			}
			arg2.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch(msg.what) {
			case MSG_USERID_FOUND: {
				Toast.makeText(this, R.string.userid_found, Toast.LENGTH_SHORT).show();
			}
			break;
			case MSG_LOGIN: {
				String text = getString(R.string.logining, msg.obj);
				Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
			}
			break;
			case MSG_AUTH_CANCEL: {
				Toast.makeText(this, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
			}
			break;
			case MSG_AUTH_ERROR: {
				Toast.makeText(this, R.string.auth_error, Toast.LENGTH_SHORT).show();
			}
			break;
			case MSG_AUTH_COMPLETE: {
				Toast.makeText(this, R.string.auth_complete, Toast.LENGTH_SHORT).show();
			}
			break;
		}
		return false;
	}
	
	private void register(final String tel,String code,String pwd){
		request = new ProjectHttpRequestImpl(this, true);
		RequestParams params = new RequestParams();
		params.put("mobile", tel);
		params.put("code", code);
		params.put("password", pwd);
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		request.requestRegUserWithDoneHandler("", params, new AsyncHttpResponseHandler(){
			
			@Override
			public void onSuccess(String content) {
				RegisterUserBean bean = ProjectDataManage.getInstance().getRegisterUserBean();
				if (bean != null ) {
					if(bean.getCode() == 200){
						Preferences.setEditor(LoginActivity.this, "user_token", bean.getData().getMember_token());
						Intent intent = new Intent(LoginActivity.this,Register2Activity.class);
						intent.putExtra("tel", tel);
						startActivity(intent);
					}else{
						Toast.makeText(LoginActivity.this, bean.getMsg(), Toast.LENGTH_LONG).show();
					}
				}else{
					Toast.makeText(LoginActivity.this, "bean is null!!", Toast.LENGTH_LONG).show();
				}
			}
		});
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			mActManager.popActivity(REGISTER_KEY, LoginActivity.this);
		}
		return super.onKeyDown(keyCode, event);
	}
	
	
}
